/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.LoaiTaiKhoanDAO;
import dao.TaiKhoanDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;
import pojo.Loaitaikhoan;
import pojo.Taikhoan;
import pojo.Thongtintaikhoan;

/**
 *
 * @author Ngoc Linh
 */
@WebServlet(name = "signup", urlPatterns = {"/signup.do"})
public class signup extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            if (request.getCharacterEncoding() == null) {
                request.setCharacterEncoding("UTF-8");
            }

            HttpSession session = request.getSession();
            if (session.getAttribute("taiKhoan") != null) {
                response.sendRedirect("index.do");
                return;
            }

            String url = "signup.jsp";

            if (request.getParameter("sign_up") != null) {
                String tenTK = request.getParameter("user_name");
                String matKhau = request.getParameter("password");
                String email = request.getParameter("email");
                String hoTen = request.getParameter("fullname");
                String gioiTinh = request.getParameter("gender");
                String ngaySinh = request.getParameter("birthday");
                String diaChi = request.getParameter("address");
                String dienThoai = request.getParameter("fone");

                request.setAttribute("tenTK", tenTK);
                request.setAttribute("matKhau", matKhau);
                request.setAttribute("lapMatKhau", request.getParameter("repass"));
                request.setAttribute("email", email);
                request.setAttribute("hoTen", hoTen);
                request.setAttribute("gioiTinh", gioiTinh);
                request.setAttribute("ngaySinh", ngaySinh);
                request.setAttribute("diaChi", diaChi);
                request.setAttribute("dienThoai", dienThoai);

                //Check captcha:
                String remoteAddr = request.getRemoteAddr();
                ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
                reCaptcha.setPrivateKey("6LerlcgSAAAAAKtqZ-i0pyUjyydapnlv2emH1UBD");

                String challenge = request.getParameter("recaptcha_challenge_field");
                String uresponse = request.getParameter("recaptcha_response_field");
                ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
                if (reCaptchaResponse.isValid()) {

                    if (TaiKhoanDAO.KiemTraTonTai(tenTK)) {
                        request.setAttribute("message", "Tên tài khoản đã tồn tại. Vui lòng chọn tên tài khoản khác !");
                    } else {
                        Taikhoan taiKhoan = new Taikhoan();
                        taiKhoan.setTenTaiKhoan(tenTK);
                        taiKhoan.setMatKhau(matKhau);
                        taiKhoan.setNgayDangKi(new Date());
                        taiKhoan.setAvatar("images/data/avatar/no_avatar.jpg");
                        taiKhoan.setDaKhoa(false);
                        taiKhoan.setDaXoa(false);
                        taiKhoan.setLoaitaikhoan(LoaiTaiKhoanDAO.LayLoaiTaiKhoan(2));
                        taiKhoan.setDiemTinCayBan((float) 0);
                        taiKhoan.setDiemTinCayMua((float) 0);
                        taiKhoan.setTrangThai(Boolean.TRUE);

                        Thongtintaikhoan thongtinTK = new Thongtintaikhoan();
                        thongtinTK.setDiaChi(diaChi);
                        thongtinTK.setEmail(email);
                        thongtinTK.setGioiTinh(gioiTinh);
                        thongtinTK.setHoTen(hoTen);
                        thongtinTK.setSoDienThoai(dienThoai);
                        thongtinTK.setTaikhoan(taiKhoan);
                        thongtinTK.setNgaySinh(util.UtilCommon.ConvertToDate(ngaySinh));
                        taiKhoan.getThongtintaikhoans().add(thongtinTK);

                        boolean bDone = TaiKhoanDAO.ThemTaiKhoanMoi(taiKhoan);
                        if (bDone) {
                            session.setAttribute("taiKhoan", taiKhoan);
                            request.setAttribute("message", "Chúc mừng bạn đã là thành viên của <a href='index.do'>P2TBid</a> ! Hi vọng bạn sẽ có những phút giây vui vẻ khi tham gia đấu giá và giành được những món hàng quý giá !");
                        } else {
                            request.setAttribute("message", "Đã có lỗi trong quá trình đăng ký tài khoản. Vui lòng thử lại sau !");
                        }
                    }
                } else {
                    request.setAttribute("message", "Mã xác nhận bạn điền không chính xác ! Xin thử lại ... (chú ý caps lock ??)");
                }
            }

            RequestDispatcher rd = request.getRequestDispatcher(url);
            rd.forward(request, response);
        } catch (Exception ex) {
            response.sendRedirect("errorpage.do");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
